<script setup lang="ts">
import {
  clearExerciseHistoryCacheUtil,
  clearFoodHistoryCacheUtil,
  getExerciseDislikeIdsUtil,
  getFoodDislikeIdsUtil,
} from '@/AGC/utils/dislike'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'

const props = defineProps(['modelValue', 'names', 'title'])
const emits = defineEmits(['update:modelValue', 'success'])
const name = ref('')
const dislikeIds = ref<number[]>([])
// 确认按钮点击事件
const onConfirm = () => {
  if (props.names.length > 0) {
    if (!name.value && props.title.includes('口味')) {
      ElMessage.error('请选择食物')
      return
    } else if (!name.value && props.title.includes('运动')) {
      ElMessage.error('请选择运动')
      return
    }

    emits('success', name.value)
  }

  emits('update:modelValue', false)
}
// 获取用户不喜欢的食物|运动 的ids
const getDislikeIds = async () => {
  try {
    if (props.title.includes('口味')) {
      dislikeIds.value = await getFoodDislikeIdsUtil()
    } else {
      dislikeIds.value = await getExerciseDislikeIdsUtil()
    }
  } catch (error) {
    Promise.reject(error)
  }
}
// 清除历史缓存
const clearHistoryCache = async () => {
  try {
    if (props.title.includes('口味')) {
      await clearFoodHistoryCacheUtil()
    } else {
      await clearExerciseHistoryCacheUtil()
    }
    ElMessage.success('清除历史缓存成功，请再次尝试')
  } catch (error) {
    ElMessage.error('清除失败, 请稍后再试')
    Promise.reject(error)
  }

  emits('update:modelValue', false)
}
</script>

<template>
  <el-dialog :model-value="modelValue" :title="title" width="500" center @open="getDislikeIds">
    <el-radio-group v-model="name" v-if="names.length > 0">
      <el-radio :value="item" size="large" v-for="item in names" :key="item">{{ item }}</el-radio>
    </el-radio-group>
    <div v-else class="empty-container">
      <!-- <el-empty description="暂无食物" /> -->
      <span v-if="dislikeIds.length > 0">
        抱歉，没有找到可以替代的{{ title.includes('口味') ? '食物' : '运动' }}，可以尝试
        <el-button type="text" @click="clearHistoryCache">清除历史缓存</el-button>
      </span>
      <span v-else>
        抱歉，小康途能力有限，没有找到可以替代的{{ title.includes('口味') ? '食物' : '运动' }}
      </span>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="emits('update:modelValue', false)">取消</el-button>
        <el-button type="primary" @click="onConfirm"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="less">
.el-radio-group {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}

.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
